package org.btik.video.server.push.udp;

import org.btik.video.server.iface.VideoChannel;

import java.net.DatagramPacket;
import java.net.InetAddress;

/**
 * @author lustre
 * @since 2023/4/27 9:43
 */
public class RawUdpVideoChannel implements VideoChannel {

    private final String channelId;
    private RawUdpVideoServer rawUdpVideoServer;

    private volatile DatagramPacket datagramPacket;

    private static final int PAYLOAD_LIMIT = 1360;

    public void setAddress(InetAddress address, int port) {
        DatagramPacket datagramPacket = new DatagramPacket(new byte[0], 0);
        datagramPacket.setAddress(address);
        datagramPacket.setPort(port);
        this.datagramPacket = datagramPacket;
    }

    public void setRawUdpVideoServer(RawUdpVideoServer rawUdpVideoServer) {
        this.rawUdpVideoServer = rawUdpVideoServer;
    }

    @Override
    public void sendFrame(byte[] frame, int len) {
        if (datagramPacket == null) {
            return;
        }
        int count = len / PAYLOAD_LIMIT;
        for (int i = 0; i < count; i++) {
            datagramPacket.setData(frame, i * PAYLOAD_LIMIT, PAYLOAD_LIMIT);
            rawUdpVideoServer.sendFrame(datagramPacket);
        }
        int lastLen = len % PAYLOAD_LIMIT;
        if (lastLen > 0) {
            datagramPacket.setData(frame, count * PAYLOAD_LIMIT, lastLen);
            rawUdpVideoServer.sendFrame(datagramPacket);
        }


    }


    public RawUdpVideoChannel(String channelId) {
        this.channelId = channelId;

    }


    @Override
    public String channelId() {
        return channelId;
    }

}
